#pragma once

#include <iostream>
#include <string>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <ctime>
#include <stdarg.h>

#define NORMALFILE "log.txt"
#define BUGFILE "log.errno"

#define DEBUG 0
#define SUCESS 1
#define WARNING 2
#define ERRNO 3
#define FATAL 4

enum
{
    SOCKET_ERRON = 1,
    BIND_ERRNO = 2,
    LISTEN_ERRON = 3,
    WRITE_ERRON = 4,
    CONNECT_ERRON = 5
};

std::string to_levelstring(int def)
{
    switch (def)
    {
    case 0:
        return "DEBUG";
    case 1:
        return "SUCESS";
    case 2:
        return "WARNING";
    case 3:
        return "ERRNO";
    case 4:
        return "FATAL";

    default:
        return nullptr;
    }
}

void logmessage(int level, const char *formet, ...)
{

    std::time_t currentTime = std::time(nullptr); // 获取当前时间的时间戳
    // 将时间戳转换为本地时间结构体
    std::tm *localTimeInfo = std::localtime(&currentTime);

    // 格式化输出为本地时间
    char buffer[1024];
    std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTimeInfo);
    // std::cout << "当前本地时间: " << buffer << std::endl;

    char prevbuffer[1024];
    snprintf(prevbuffer, sizeof prevbuffer, "[%s][%s][pid:%d]", to_levelstring(level).c_str(), buffer, getpid());

    char nextmessage[1024];

    va_list arg;
    va_start(arg, formet);

    vsnprintf(nextmessage, sizeof nextmessage, formet, arg);

    std::cout << prevbuffer << nextmessage << std::endl;

    // 因为我重定向了012文件，所以我们把错误信息打印到两个文件中，真正实现日志的功能
    // FILE *sucessfile = fopen(NORMALFILE, "a");
    // FILE *failfile = fopen(BUGFILE, "a");

    // if (level == DEBUG || level == SUCESS || level == WARNING)
    //     fprintf(sucessfile,"[%s][%s]\n", prevbuffer, nextmessage);
    // else
    //     fprintf(failfile,"%s%s\n", prevbuffer, nextmessage);

    // fclose(sucessfile);
    // fclose(failfile);

}